<template>
  <div class="menu-permission-binding">
    <div class="page-header">
      <h2>菜单权限绑定管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData" :icon="Refresh">刷新数据</el-button>
      </div>
    </div>

    <div class="content-container">
      <!-- 左侧菜单树 -->
      <div class="menu-tree-panel">
        <div class="panel-header">
          <h3>菜单列表</h3>
          <el-input
            v-model="menuSearchText"
            placeholder="搜索菜单"
            size="small"
            clearable
            :prefix-icon="Search"
          />
        </div>
        <div class="tree-container">
          <el-tree
            ref="menuTreeRef"
            :data="menuTreeData"
            :props="menuTreeProps"
            :filter-node-method="filterMenuNode"
            node-key="id"
            highlight-current
            @current-change="handleMenuSelect"
            class="menu-tree"
          >
            <template #default="{ node, data }">
              <div class="menu-tree-node">
                <el-icon v-if="data.icon" class="menu-icon">
                  <component :is="data.icon" />
                </el-icon>
                <span class="menu-name">{{ data.menuName }}</span>
                <el-tag 
                  :type="getMenuTypeTag(data.menuType)" 
                  size="small"
                  class="menu-type-tag"
                >
                  {{ getMenuTypeText(data.menuType) }}
                </el-tag>
              </div>
            </template>
          </el-tree>
        </div>
      </div>

      <!-- 右侧权限管理 -->
      <div class="permission-panel">
        <div class="panel-header">
          <h3>权限绑定管理</h3>
          <div class="header-actions" v-if="selectedMenu">
            <el-button 
              type="primary" 
              @click="savePermissionBinding" 
              :loading="saving"
              :disabled="!hasChanges"
            >
              保存绑定
            </el-button>
            <el-button @click="resetPermissionBinding">重置</el-button>
          </div>
        </div>

        <div v-if="!selectedMenu" class="empty-state">
          <el-empty description="请选择一个菜单来管理权限绑定" />
        </div>

        <div v-else class="permission-content">
          <!-- 选中菜单信息 -->
          <div class="selected-menu-info">
            <div class="menu-info-card">
              <div class="menu-title">
                <el-icon v-if="selectedMenu.icon" class="title-icon">
                  <component :is="selectedMenu.icon" />
                </el-icon>
                <span class="title-text">{{ selectedMenu.menuName }}</span>
                <el-tag 
                  :type="getMenuTypeTag(selectedMenu.menuType)" 
                  size="small"
                >
                  {{ getMenuTypeText(selectedMenu.menuType) }}
                </el-tag>
              </div>
              <div class="menu-details">
                <div class="detail-item">
                  <span class="label">菜单编码：</span>
                  <code class="value">{{ selectedMenu.menuCode }}</code>
                </div>
                <div class="detail-item" v-if="selectedMenu.path">
                  <span class="label">路由路径：</span>
                  <code class="value">{{ selectedMenu.path }}</code>
                </div>
              </div>
            </div>
          </div>

          <!-- 权限搜索 -->
          <div class="permission-search">
            <el-input
              v-model="permissionSearchText"
              placeholder="搜索权限"
              size="small"
              clearable
              :prefix-icon="Search"
            />
          </div>

          <!-- 权限树 -->
          <div class="permission-tree-container">
            <el-tree
              ref="permissionTreeRef"
              :data="permissionTreeData"
              :props="permissionTreeProps"
              :filter-node-method="filterPermissionNode"
              show-checkbox
              node-key="id"
              check-strictly
              @check="handlePermissionCheck"
              class="permission-tree"
            >
              <template #default="{ node, data }">
                <div class="permission-tree-node">
                  <span class="permission-name">{{ data.permissionName }}</span>
                  <el-tag 
                    :type="getPermissionTypeTag(data.permissionType)"
                    size="small"
                    class="permission-type-tag"
                  >
                    {{ getPermissionTypeName(data.permissionType) }}
                  </el-tag>
                  <code v-if="data.permissionCode" class="permission-code">
                    {{ data.permissionCode }}
                  </code>
                </div>
              </template>
            </el-tree>
          </div>

          <!-- 绑定选项 -->
          <div class="binding-options">
            <el-card shadow="never">
              <template #header>
                <span>绑定选项</span>
              </template>
              <div class="options-content">
                <el-checkbox v-model="autoAssignToRoles">
                  自动将绑定的权限分配给拥有此菜单的角色
                </el-checkbox>
                <el-tooltip content="启用此选项后，当保存权限绑定时，系统会自动将这些权限分配给所有拥有此菜单的角色">
                  <el-icon class="help-icon"><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </el-card>
          </div>

          <!-- 当前绑定统计 -->
          <div class="binding-stats" v-if="currentBindings.length > 0">
            <el-card shadow="never">
              <template #header>
                <span>当前绑定权限详情</span>
              </template>
              <div class="stats-content">
                <div class="stat-item">
                  <span class="stat-label">已绑定权限：</span>
                  <span class="stat-value">{{ currentBindings.length }} 个</span>
                </div>
                
                <!-- 权限详细列表 -->
                <div class="bound-permissions-detail">
                  <div 
                    v-for="permission in boundPermissionDetails" 
                    :key="permission.id"
                    class="permission-detail-item"
                  >
                    <div class="permission-header">
                      <el-tag 
                        :type="getPermissionTypeTag(permission.permissionType)"
                        size="small"
                        class="permission-type"
                      >
                        {{ getPermissionTypeName(permission.permissionType) }}
                      </el-tag>
                      <span class="permission-name">{{ permission.permissionName }}</span>
                    </div>
                    
                    <div class="permission-info">
                      <div class="info-item">
                        <span class="info-label">权限编码：</span>
                        <code class="info-value">{{ permission.permissionCode }}</code>
                      </div>
                      
                      <div v-if="permission.description" class="info-item">
                        <span class="info-label">权限描述：</span>
                        <span class="info-value">{{ permission.description }}</span>
                      </div>
                      
                      <div v-if="permission.resourceUrl" class="info-item">
                        <span class="info-label">资源地址：</span>
                        <code class="info-value">{{ permission.method || 'GET' }} {{ permission.resourceUrl }}</code>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Search, QuestionFilled } from '@element-plus/icons-vue'
import request from '../utils/request'
import { usePermissions } from '../stores/permission'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const menuTreeRef = ref()
const permissionTreeRef = ref()
const menuTreeData = ref([])
const permissionTreeData = ref([])
const selectedMenu = ref(null)
const currentBindings = ref([])
const originalBindings = ref([])
const menuSearchText = ref('')
const permissionSearchText = ref('')
const autoAssignToRoles = ref(true)

// 树形组件配置
const menuTreeProps = {
  children: 'children',
  label: 'menuName'
}

const permissionTreeProps = {
  children: 'children',
  label: 'permissionName'
}

// 权限检查
const { hasPermission } = usePermissions()

// 计算属性
const hasChanges = computed(() => {
  if (!selectedMenu.value) return false
  
  const currentIds = currentBindings.value.sort()
  const originalIds = originalBindings.value.sort()
  
  return JSON.stringify(currentIds) !== JSON.stringify(originalIds)
})

const boundPermissionNames = computed(() => {
  if (!currentBindings.value || !permissionTreeData.value) return []
  
  const allPermissions = flattenPermissions(permissionTreeData.value)
  return allPermissions.filter(p => currentBindings.value.includes(p.id))
})

const boundPermissionDetails = computed(() => {
  if (!currentBindings.value || !permissionTreeData.value) return []
  
  const allPermissions = flattenPermissions(permissionTreeData.value)
  return allPermissions
    .filter(p => currentBindings.value.includes(p.id))
    .sort((a, b) => {
      // 按权限类型排序：MENU -> OPERATION -> DATA -> API -> BUTTON
      const typeOrder = { 'MENU': 1, 'OPERATION': 2, 'DATA': 3, 'API': 4, 'BUTTON': 5 }
      const aOrder = typeOrder[a.permissionType] || 99
      const bOrder = typeOrder[b.permissionType] || 99
      
      if (aOrder !== bOrder) {
        return aOrder - bOrder
      }
      
      // 同类型按名称排序
      return a.permissionName.localeCompare(b.permissionName)
    })
})

// 展平权限树
const flattenPermissions = (permissions) => {
  let result = []
  for (const permission of permissions) {
    result.push(permission)
    if (permission.children && permission.children.length > 0) {
      result = result.concat(flattenPermissions(permission.children))
    }
  }
  return result
}

// 监听搜索文本变化
watch(menuSearchText, (val) => {
  menuTreeRef.value?.filter(val)
})

watch(permissionSearchText, (val) => {
  permissionTreeRef.value?.filter(val)
})

// 过滤节点方法
const filterMenuNode = (value, data) => {
  if (!value) return true
  return data.menuName.toLowerCase().includes(value.toLowerCase()) ||
         (data.menuCode && data.menuCode.toLowerCase().includes(value.toLowerCase()))
}

const filterPermissionNode = (value, data) => {
  if (!value) return true
  return data.permissionName.toLowerCase().includes(value.toLowerCase()) ||
         (data.permissionCode && data.permissionCode.toLowerCase().includes(value.toLowerCase()))
}

// 获取菜单数据
const fetchMenuData = async () => {
  try {
    loading.value = true
    const response = await request.get('/admin/menu-management/tree')
    menuTreeData.value = response.data || []
  } catch (error) {
    console.error('获取菜单数据失败:', error)
    ElMessage.error('获取菜单数据失败')
  } finally {
    loading.value = false
  }
}

// 获取权限数据
const fetchPermissionData = async () => {
  try {
    const response = await request.get('/permission/list')
    permissionTreeData.value = response.data || []
  } catch (error) {
    console.error('获取权限数据失败:', error)
    ElMessage.error('获取权限数据失败')
  }
}

// 处理菜单选择
const handleMenuSelect = async (data) => {
  if (!data) return
  
  selectedMenu.value = data
  await fetchMenuPermissions(data.id)
}

// 获取菜单权限绑定
const fetchMenuPermissions = async (menuId) => {
  try {
    const response = await request.get(`/admin/menu-management/${menuId}/permissions`)
    const permissionIds = response.data || []
    
    currentBindings.value = [...permissionIds]
    originalBindings.value = [...permissionIds]
    
    // 设置权限树的选中状态
    await nextTick()
    if (permissionTreeRef.value) {
      permissionTreeRef.value.setCheckedKeys(permissionIds)
    }
  } catch (error) {
    console.error('获取菜单权限失败:', error)
    ElMessage.error('获取菜单权限失败')
  }
}

// 处理权限选中变化
const handlePermissionCheck = (data, checkedInfo) => {
  currentBindings.value = checkedInfo.checkedKeys
}

// 保存权限绑定
const savePermissionBinding = async () => {
  if (!selectedMenu.value) return
  
  try {
    saving.value = true
    
    const bindData = {
      menuId: selectedMenu.value.id,
      permissionIds: currentBindings.value,
      autoAssignToRoles: autoAssignToRoles.value
    }
    
    await request.post(`/admin/menu-management/${selectedMenu.value.id}/permissions`, bindData)
    
    ElMessage.success('权限绑定保存成功')
    originalBindings.value = [...currentBindings.value]
    
  } catch (error) {
    console.error('保存权限绑定失败:', error)
    ElMessage.error('保存权限绑定失败')
  } finally {
    saving.value = false
  }
}

// 重置权限绑定
const resetPermissionBinding = async () => {
  if (!selectedMenu.value) return
  
  currentBindings.value = [...originalBindings.value]
  
  await nextTick()
  if (permissionTreeRef.value) {
    permissionTreeRef.value.setCheckedKeys(originalBindings.value)
  }
  
  ElMessage.info('已重置权限绑定')
}

// 刷新数据
const refreshData = async () => {
  await Promise.all([
    fetchMenuData(),
    fetchPermissionData()
  ])
  
  if (selectedMenu.value) {
    await fetchMenuPermissions(selectedMenu.value.id)
  }
  
  ElMessage.success('数据刷新成功')
}

// 获取菜单类型标签
const getMenuTypeTag = (type) => {
  switch (type) {
    case 'DIRECTORY': return 'warning'
    case 'MENU': return 'primary'
    case 'BUTTON': return 'success'
    default: return 'info'
  }
}

// 获取菜单类型文本
const getMenuTypeText = (type) => {
  switch (type) {
    case 'DIRECTORY': return '目录'
    case 'MENU': return '菜单'
    case 'BUTTON': return '按钮'
    default: return '未知'
  }
}

// 获取权限类型标签
const getPermissionTypeTag = (type) => {
  switch (type) {
    case 'MENU': return 'success'
    case 'OPERATION': return 'primary'
    case 'DATA': return 'warning'
    case 'API': return 'danger'
    case 'BUTTON': return 'info'
    default: return 'info'
  }
}

    // 获取权限类型名称
    const getPermissionTypeName = (type) => {
      switch (type) {
        case 'MENU': return '菜单'
        case 'OPERATION': return '操作'
        case 'DATA': return '数据'
        case 'API': return '接口'
        case 'BUTTON': return '按钮'
        default: return '未知'
      }
    }

// 页面加载时获取数据
onMounted(async () => {
  await Promise.all([
    fetchMenuData(),
    fetchPermissionData()
  ])
})
</script>

<style scoped>
.menu-permission-binding {
  background: white;
  border-radius: 8px;
  padding: 20px;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e6e6e6;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.content-container {
  display: flex;
  gap: 20px;
  flex: 1;
  overflow: hidden;
}

.menu-tree-panel {
  width: 300px;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
}

.permission-panel {
  flex: 1;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 15px;
  border-bottom: 1px solid #e6e6e6;
  background: #f8f9fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

.tree-container {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.menu-tree,
.permission-tree {
  height: 100%;
}

.menu-tree-node,
.permission-tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
  padding: 5px 0;
}

.menu-icon {
  color: #409EFF;
}

.menu-name,
.permission-name {
  flex: 1;
  font-size: 14px;
  color: #303133;
}

.menu-type-tag,
.permission-type-tag {
  flex-shrink: 0;
}

.permission-code {
  flex-shrink: 0;
  background: #f4f4f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 12px;
  color: #909399;
  border: 1px solid #e4e7ed;
}

.permission-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.selected-menu-info {
  margin-bottom: 20px;
}

.menu-info-card {
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  padding: 15px;
  background: #f8f9fa;
}

.menu-title {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.title-icon {
  color: #409EFF;
  font-size: 18px;
}

.title-text {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.menu-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.label {
  font-size: 14px;
  color: #606266;
  min-width: 80px;
}

.value {
  background: #f4f4f5;
  padding: 2px 8px;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 12px;
  color: #303133;
  border: 1px solid #e4e7ed;
}

.permission-search {
  margin-bottom: 15px;
}

.permission-tree-container {
  flex: 1;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  overflow: hidden;
}

.binding-options {
  margin-top: 20px;
}

.options-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.help-icon {
  color: #909399;
  cursor: help;
}

.binding-stats {
  margin-top: 20px;
}

.stats-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 14px;
  font-weight: 600;
  color: #409EFF;
}

.bound-permissions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.bound-permission-tag {
  font-size: 12px;
}

/* 权限详情样式 */
.bound-permissions-detail {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
}

.permission-detail-item {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 12px;
  background: #fafafa;
  transition: all 0.3s ease;
}

.permission-detail-item:hover {
  border-color: #409EFF;
  background: #f0f9ff;
}

.permission-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.permission-type {
  flex-shrink: 0;
}

.permission-name {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.permission-info {
  display: flex;
  flex-direction: column;
  gap: 6px;
  padding-left: 8px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.info-label {
  font-size: 12px;
  color: #909399;
  min-width: 70px;
  flex-shrink: 0;
}

.info-value {
  font-size: 12px;
  color: #606266;
  word-break: break-all;
}

.info-value code,
code.info-value {
  background: #f4f4f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', monospace;
  border: 1px solid #e4e7ed;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .content-container {
    flex-direction: column;
  }
  
  .menu-tree-panel {
    width: 100%;
    height: 200px;
  }
  
  .permission-panel {
    height: calc(100vh - 400px);
  }
}
</style> 